package com.netrust.quarz.aspect;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class HttpAspect {
	
	private static final Logger logger = LoggerFactory.getLogger(HttpAspect.class);
	
	
	 	@Pointcut("execution(public * com.netrust.quarz.controller.*.*(..))")//要处理的方法，包名+类名+方法名
	    public void cut(){
	 		
	    }

	    @Before("cut()")//在调用上面 @Pointcut标注的方法前执行以下方法
	    public void doBefore(JoinPoint joinPoint){//用于获取类方法
	    	ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
	        HttpServletRequest request =  attributes.getRequest();
	        //url
	        logger.info("url ={}",request.getRequestURI());
	        //method
	        logger.info("method={}",request.getMethod());
	        //ip
	        logger.info("ip={}",request.getRemoteAddr());
	        //类方法
	        logger.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName()+'.'+ joinPoint.getSignature().getName());//获取类名及类方法
	        //参数
	        logger.info("args={}",joinPoint.getArgs());	        
	    }
	    
	    @After("cut()")
	    public void doAfter(){
	        logger.info(">>>>>>完成controller调用>>>>>>");
	    }
	    

	    @AfterReturning(returning = "obj",pointcut = "cut()")//在调用上面 @Pointcut标注的方法后执行。用于获取返回值
	    public void doAfterReturning(Object obj){
	    	if(obj==null){
	    		logger.info("返回={}","null");	    		
	    	}else{	    		
	    		logger.info("返回={}",obj.toString());	    		
	    	}
	    }
	    
	    
	    @AfterThrowing(pointcut = "cut()",throwing = "e")//切点异常【抛出
	    public void doAfterThrowing(JoinPoint joinPoint,  Throwable e){
	    	logger.error("异常 >>>> {} ",ExceptionUtils.getStackTrace(e));
	    }
}
